package com.shi.yoyoshop.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shi.yoyoshop.bean.Goods;
import com.shi.yoyoshop.bean.Top;
import com.shi.yoyoshop.bean.Type;
import com.shi.yoyoshop.dto.AddGoodsDto;
import com.shi.yoyoshop.dto.EditGoodsDto;
import com.shi.yoyoshop.service.GoodsService;
import com.shi.yoyoshop.service.TopService;
import com.shi.yoyoshop.service.TypeService;
import com.shi.yoyoshop.util.FileUtil;
import com.shi.yoyoshop.util.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class GoodsController {
    @Resource
    private GoodsService goodsService;
    @Resource
    private TypeService typeService;

    @Resource
    private TopService topService;

    /**
     * 商品用户详情接口
     *
     * @param request
     * @return
     */
    @GetMapping("/index/detail")
    public String goodsDetails(HttpServletRequest request) {
        int goodId = Integer.parseInt(request.getParameter("goodid"));
        Goods goods = goodsService.getGoodsAndTypeByGoodsId(goodId);
        request.setAttribute("good", goods);
        return "/index/detail.jsp";
    }

    /**
     * header 商品分类接口
     *
     * @param request
     * @return
     */
    @GetMapping("/index/goods")
    public String getGoodsByTypeIdWithPage(HttpServletRequest request,
                                           @RequestParam("typeid") Integer typeId,
                                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "size", defaultValue = "4") Integer pageSize) {
        Page<Goods> pageInfo = goodsService.getGoodsListByTypeIdWithPage(new Page<Goods>(page, pageSize), typeId);
        request.setAttribute("flag", 2);
        request.setAttribute("goodList", pageInfo.getRecords());
        request.setAttribute("pageTool", PageUtil.getPageTool(request, pageInfo.getTotal(), page, pageSize));
        return "/index/goods.jsp";
    }

    /**
     * header 热销、新品接口
     *
     * @param request
     * @param typeId
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/index/top")
    public String getGoodsByHotTypeIdWithPage(HttpServletRequest request,
                                              @RequestParam("typeid") Integer typeId,
                                              @RequestParam(value = "page", defaultValue = "1") Integer page,
                                              @RequestParam(value = "size", defaultValue = "4") Integer pageSize) {
        Page<Goods> pageInfo = goodsService.getGoodsListByHotTypeIdWithPage(new Page<Goods>(page, pageSize), typeId);
        request.setAttribute("flag", typeId + 5);
        request.setAttribute("goodList", pageInfo.getRecords());
        request.setAttribute("pageTool", PageUtil.getPageTool(request, pageInfo.getTotal(), page, pageSize));
        return "/index/goods.jsp";
    }


    /**
     * 模糊搜索商品
     *
     * @param name
     * @param page
     * @param size
     * @return
     */
    @PostMapping("/index/search")
    public String search(HttpServletRequest request, String name, Integer page, Integer size) {
        Page<Goods> pageInfo = goodsService.getGoodsListByNameLikeWithPage(new Page<Goods>(page, size), name);
        request.setAttribute("goodList", pageInfo.getRecords());
        String pageTool = PageUtil.getPageTool(request, pageInfo.getTotal(), page, size);
        request.setAttribute("pageTool", pageTool);
        return "/index/goods.jsp";
    }

    /**
     * 后台查看商品分页列表
     *
     * @param request
     * @param page
     * @param size
     * @param status
     * @return
     */
    @GetMapping("/admin/goodsList")
    public String searchGoodsListWithPage(HttpServletRequest request, Integer page, Integer size, Integer status) {
        List<Goods> goodsList = goodsService.getGoodsList();
        goodsList.forEach(item -> {
            // 为goods补充 type
            Type type = typeService.getOneByTypeId(item.getTypeId());
            item.setType(type);
            // 为goods设置 热销|新品|今日推荐类型
            List<Top> topList = topService.getTopListByGoodsId(item.getId());
            topList.forEach(top -> {
                if (top.getType().equals(1)) {
                    item.setTopToday(true);
                }
                if (top.getType().equals(2)) {
                    item.setTopHot(true);
                }
                if (top.getType().equals(3)) {
                    item.setTopNew(true);
                }
            });
        });
        if (status.equals(1)) {
            goodsList = goodsList.stream().filter(goods -> goods.getTopToday().equals(true)).collect(Collectors.toList());
        }
        if (status.equals(2)) {
            goodsList = goodsList.stream().filter(goods -> goods.getTopHot().equals(true)).collect(Collectors.toList());
        }
        if (status.equals(3)) {
            goodsList = goodsList.stream().filter(goods -> goods.getTopNew().equals(true)).collect(Collectors.toList());
        }
        // 分类过滤之后的总条目数
        int total = goodsList.size();
        int start = (page - 1) * size;
        int end = start + size;
        if (end > total) {
            end = total;
        }
        goodsList = goodsList.subList(start, end);
        String pageTool = PageUtil.getPageTool(request, total, page, size);
        request.setAttribute("status", status);
        request.setAttribute("pageTool", pageTool);
        request.setAttribute("goodsList", goodsList);
        return "/admin/goods_list.jsp";
    }

    /**
     * 加入或移出 热销|新品|条幅
     *
     * @param operate
     * @param goodsId
     * @param type
     * @return
     */
    @Transactional
    @ResponseBody
    @PostMapping("/admin/topOperate")
    public String topOperate(String operate, Integer goodsId, Integer type) {
        if ("delete".equals(operate)) {
            topService.removeByGoodsIdAndType(goodsId, type);
        }
        if ("join".equals(operate)) {
            Top top = new Top();
            top.setGoodId(goodsId);
            top.setType(type);
            topService.save(top);
        }
        return "ok";
    }

    @GetMapping("/admin/goodsDelete")
    public String removeGoods(Integer id, Integer status) {
        goodsService.removeGoodsById(id);
        return "redirect:/admin/goodsList?page=1&size=6&status=" + status;
    }

    @GetMapping("/admin/goodsEdit")
    public String toEditGoods(HttpServletRequest request, Integer id, Integer status) {
        Goods goods = goodsService.getGoodsById(id);
        Type type = typeService.getOneByTypeId(goods.getTypeId());
        goods.setType(type);
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("goods", goods);
        request.setAttribute("typeList", typeList);
        request.setAttribute("status", status);
        return "/admin/goods_edit.jsp";
    }

    @PostMapping("/admin/goodsEdit")
    public String editGoods(EditGoodsDto editGoodsDto) throws IOException {
        String cover = FileUtil.upload(editGoodsDto.getCover());
        String image1 = FileUtil.upload(editGoodsDto.getImage1());
        String image2 = FileUtil.upload(editGoodsDto.getImage2());
        Goods goods = new Goods();
        BeanUtils.copyProperties(editGoodsDto, goods, "cover", "image1", "image2");
        goods.setCover(cover);
        goods.setImage1(image1);
        goods.setImage2(image2);
        goodsService.modifyGoodsById(goods);
        return "redirect:/admin/goodsList?page=1&size=6&status=" + editGoodsDto.getTopType();
    }

    @GetMapping("/admin/goodsAdd")
    public String toAddGoods(HttpServletRequest request) {
        List<Type> typeList = typeService.getTypeList();
        request.setAttribute("typeList", typeList);
        return "/admin/goods_add.jsp";
    }


    @PostMapping("/admin/goodsAdd")
    public String addGoods(AddGoodsDto addGoodsDto) throws IOException {
        String cover = FileUtil.upload(addGoodsDto.getCover());
        String image1 = FileUtil.upload(addGoodsDto.getImage1());
        String image2 = FileUtil.upload(addGoodsDto.getImage2());
        Goods goods = new Goods();
        BeanUtils.copyProperties(addGoodsDto, goods, "cover", "image1", "image2");
        goods.setTopNew(null);
        goods.setTopHot(null);
        goods.setTopToday(null);
        goods.setCover(cover);
        goods.setImage1(image1);
        goods.setImage2(image2);
        goods.setStatus(1);
        goodsService.save(goods);
        return "redirect:/admin/goodsList?page=1&size=6&status=0";
    }
}
